package com.example.springbatchsample.controller;

import org.springframework.batch.core.*;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 主要的控制器
 *
 * @author Yunkai Luo
 * @since 2022/1/21
 **/
@RestController
public class MainController {

    @Autowired
    private Job handleUserJobx;

    @Autowired
    private JobLauncher jobLauncher;


    @GetMapping("/hello")
    public String getHello() {
        return "Hello";
    }

    @GetMapping("/hellox")
    public BatchStatus getHello(@RequestParam String msg) throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException {
        //传参数给任务
        JobParameters parameters = new JobParametersBuilder()
                .addString("msg", msg)
                .toJobParameters();
        //启动任务并把参数传给任务
        JobExecution job = jobLauncher.run(handleUserJobx, parameters);
        return job.getStatus();
    }

}
